"""
FastAPI主应用程序
"""
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware
from fastapi.responses import JSONResponse
from fastapi.staticfiles import StaticFiles
from loguru import logger
import time

from app.core.config import settings
from app.core.database import register_database
from app.utils.redis_client import init_redis, close_redis
from app.api import cargo, tracking, websocket, auth

# 创建FastAPI应用实例
app = FastAPI(
    title=settings.app_name,
    version=settings.version,
    description="客、货、装备信息管理、追踪、监控实验平台",
    docs_url="/docs" if settings.debug else None,
    redoc_url="/redoc" if settings.debug else None,
)

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.cors_origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 添加可信主机中间件
app.add_middleware(
    TrustedHostMiddleware,
    allowed_hosts=["*"] if settings.debug else ["localhost", "127.0.0.1"]
)


# 请求处理时间中间件
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    start_time = time.time()
    response = await call_next(request)
    process_time = time.time() - start_time
    response.headers["X-Process-Time"] = str(process_time)
    return response


# 全局异常处理器
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
    logger.error(f"全局异常处理: {exc}")
    return JSONResponse(
        status_code=500,
        content={
            "success": False,
            "message": "服务器内部错误",
            "detail": str(exc) if settings.debug else "请联系系统管理员"
        }
    )


# 注册数据库
register_database(app)

# 应用启动事件
@app.on_event("startup")
async def startup_event():
    """应用启动时执行"""
    logger.info("应用程序启动中...")

    # 初始化Redis连接（可选）
    try:
        await init_redis()
        logger.info("Redis连接初始化成功")
    except Exception as e:
        logger.warning(f"Redis连接初始化失败，将在无缓存模式下运行: {e}")
        # Redis连接失败不影响应用启动

    logger.info("应用程序启动完成")


# 应用关闭事件
@app.on_event("shutdown")
async def shutdown_event():
    """应用关闭时执行"""
    logger.info("应用程序正在关闭...")

    # 关闭Redis连接
    try:
        await close_redis()
        logger.info("Redis连接已关闭")
    except Exception as e:
        logger.warning(f"关闭Redis连接失败: {e}")

    logger.info("应用程序已关闭")


# 根路由
@app.get("/", tags=["根路由"])
async def root():
    """根路由"""
    return {
        "message": "欢迎使用客货装备信息管理追踪监控平台",
        "version": settings.version,
        "docs_url": "/docs" if settings.debug else None
    }


# 健康检查路由
@app.get("/health", tags=["健康检查"])
async def health_check():
    """健康检查"""
    return {
        "status": "healthy",
        "timestamp": time.time(),
        "version": settings.version
    }


# 注册API路由
app.include_router(auth.router, prefix="/api/v1")
app.include_router(cargo.router, prefix="/api/v1")
app.include_router(tracking.router, prefix="/api/v1")
app.include_router(websocket.router)

# 挂载静态文件
app.mount("/static", StaticFiles(directory="static"), name="static")

# 如果是调试模式，添加更多路由
if settings.debug:
    @app.get("/debug/config", tags=["调试"])
    async def debug_config():
        """调试配置信息"""
        return {
            "app_name": settings.app_name,
            "version": settings.version,
            "debug": settings.debug,
            "database_url": settings.database_url.split("@")[-1] if "@" in settings.database_url else "***",
            "redis_url": settings.redis_url,
        }
